from flask import Flask
from flask_sqlalchemy import SQLAlchemy as BaseSQLAlchemy
from contextlib import contextmanager
import os


class Application(Flask):
    def __init__(self, import_name, template_folder=None, root_path=None):
        super(Application, self).__init__(
            import_name,
            template_folder=template_folder,
            root_path=root_path,
            static_folder=None  # 不设置为空时使用项目根目录默认路径,会找不到目录
        )

        self.config.from_pyfile('config/setting.py')

        db.init_app(self)


class SQLAlchemy(BaseSQLAlchemy):
    # 利用contextmanager管理器,对try/except语句封装
    @contextmanager
    def auto_commit(self):
        try:
            yield
            self.session.commit()
        except Exception as e:
            # 加入数据库commit提交失败，回滚
            self.session.rollback()
            raise e


db = SQLAlchemy()

template_folder = os.getcwd() + "/web/templates/"
app = Application(__name__, template_folder=template_folder, root_path=os.getcwd())
app.app_context().push()
